package com.yyt.module_main.act;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.vondear.rxtool.RxImageTool;
import com.vondear.rxtool.RxPermissionsTool;
import com.vondear.rxtool.RxPhotoTool;
import com.yyt.libsrc.bean.BaseCallbackBean;
import com.yyt.libsrc.bean.BasicDocumentBean;
import com.yyt.libsrc.bean.UploadPhoteBean;
import com.yyt.libsrc.conf.Consts;
import com.yyt.libsrc.helper.LocalHelper;
import com.yyt.libsrc.helper.MsgHelper;
import com.yyt.libsrc.net.JavaParamsBuilder;
import com.yyt.libsrc.net.NetUtil;
import com.yyt.libsrc.net.SuccessCallback;
import com.yyt.libsrc.router.RouteTable;
import com.yyt.module_main.R;
import com.yyt.module_main.databinding.ActivitySysSettingBinding;
import com.yyt.module_main.home.MainActivity;
import com.yyt.module_main.vm.SysSettingVM;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import com.zhihu.matisse.listener.OnCheckedListener;
import com.zhihu.matisse.listener.OnSelectedListener;

import java.io.IOException;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.functions.Consumer;
import top.lixb.libcommon.base.RefreshableActivity;
import top.lixb.libcommon.glide.Glide4Engine;
import top.lixb.libcommon.helper.GlideHelper;
import top.lixb.libcommon.log.L;
import top.lixb.libcommon.utils.BitmapUtil;
import top.lixb.libcommon.utils.UriUtils;

@Route(path = RouteTable.main_sys_setting)
public class SysSettingActivity extends RefreshableActivity<ActivitySysSettingBinding> {

    private static final int REQUEST_CODE_CHOOSE = 111_11;
    private SysSettingVM mVm;
    private List<Uri> mSelected;

    @Override
    protected void init() {
        mVm = new SysSettingVM();
        mRefreshContentBinding.setVm(mVm);
        setTitle("设置");
        showToolbarDivider();
        mVm.setActivity(this);
        mRefreshContentBinding.ivHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RxPermissions permissions = new RxPermissions(SysSettingActivity.this);
                permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA).subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
//                            com.yyt.xbb.fileprovider
                            Matisse.from(SysSettingActivity.this)
                                    .choose(MimeType.ofImage())
                                    .countable(false)
                                    .capture(true)
                                    .captureStrategy(new CaptureStrategy(true, "com.yyt.fileprovider"))
                                    .maxSelectable(1)
                                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                    .thumbnailScale(0.85f)
                                    .imageEngine(new Glide4Engine())
                                    .forResult(REQUEST_CODE_CHOOSE);
                        }
                    }
                });

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            mSelected = Matisse.obtainResult(data);
            L.e("mSelected: " + mSelected);
            if (mSelected.size() > 0) {
                final Uri uri = mSelected.get(0);
                if (null != uri) {
                    String imgBase64 = "";
                    try {
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                        imgBase64 = BitmapUtil.Bitmap2StrByBase64(bitmap);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    NetUtil.homePost(new JavaParamsBuilder()
                            .addCmd(Consts.CMD.uploadPhoto)
                            .addP("imgBase", imgBase64)
                            .build(), new SuccessCallback<UploadPhoteBean>() {
                        @Override
                        public void onSuccess(final UploadPhoteBean uploadPhoteBean) {
                            NetUtil.sellerPost(new JavaParamsBuilder()
                                    .addCmd(Consts.CMD.head_to_save)
                                    .addP("headImg", uploadPhoteBean.data)
                                    .addP("phone", mVm.mobile.get())
                                    .build(), new SuccessCallback<BaseCallbackBean>() {
                                @Override
                                public void onSuccess(BaseCallbackBean baseCallbackBean) {
                                    MsgHelper.showToast("设置头像成功");
                                    mRefreshContentBinding.ivHead.setImageURI(uri);
                                    LocalHelper.saveHeadIconUrl(uploadPhoteBean.data);
                                }
                            });
                        }
                    });
                }
            }
        }
    }

    @Override
    protected int initRefreshLayout() {
        return R.layout.activity_sys_setting;
    }

    @Override
    protected void getData(boolean refresh) {
        showLoading();
        // TODO: 2018/8/8 获取商家基本信息
        NetUtil.sellerPost(new JavaParamsBuilder()
                .addCmd(Consts.CMD.basicDocument)
                .build(), new SuccessCallback<BasicDocumentBean>() {
            @Override
            public void onSuccess(BasicDocumentBean basicDocumentBean) {
                GlideHelper.loadImg(mRefreshContentBinding.ivHead, basicDocumentBean.data.headImg);
                mVm.IDCardNo.set(basicDocumentBean.data.icNo);
                mVm.mobile.set(basicDocumentBean.data.phone);
                mVm.uname.set(basicDocumentBean.data.realName);
                mVm.servicePhone.set("012-456789");
            }

            @Override
            public void onComplete() {
                super.onComplete();
                finishGetData();
                hideLoading();
            }
        });
    }
}
